package com.vcc.core.util;


import io.jsonwebtoken.*;
import kotlin.jvm.internal.Intrinsics;

import javax.crypto.spec.SecretKeySpec;
import jakarta.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JwtUtil {

    public static Claims parseJWT(String jsonWebToken, String base64Security) {
        try {
            byte[] bytes = DatatypeConverter.parseBase64Binary(base64Security);
            Jws jwt = Jwts.parser().setSigningKey(bytes).parseClaimsJws(jsonWebToken);
            return (Claims) jwt.getBody();
        } catch (Exception e) {
            throw e;
        }
    }


    public static String createJWT(Long userId, long expiresSecond, String base64Security, String clientIp) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long tempMillis = System.currentTimeMillis();
        Date now = new Date(tempMillis);
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        SecretKeySpec signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .claim("userId", (userId.toString()))
                .claim("expand", (clientIp))
                .signWith(signatureAlgorithm, signingKey);
        if (expiresSecond >= 0L) {
            long expMillis =  tempMillis + expiresSecond;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp)
                    .setNotBefore(now);
        }
        return builder.compact();
    }

    public static String createRoJWT(Long userId, long expiresSecond, String base64Security, String clientIp) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long tempMillis = System.currentTimeMillis();
        Date now = new Date(tempMillis);
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        SecretKeySpec signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        JwtBuilder builder = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .claim("userId", (userId.toString()))
                .claim("expand", (clientIp))
                .claim("ro", Boolean.TRUE.toString())
                .signWith(signatureAlgorithm, signingKey);
        if (expiresSecond >= 0L) {
            long expMillis =  tempMillis + expiresSecond;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp)
                    .setNotBefore(now);
        }
        return builder.compact();
    }

}
